package com.lunevich.demo.helpers;

import com.lunevich.demo.R;
import com.lunevich.demo.common.GetSystemService;

import android.content.Context;
import android.graphics.Bitmap;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class DownloadManager {

	public static final String IMAGE_DOWNLOADER = "=IMAGE_DOWNLOADER=";
	private AsyncTaskManager asyncTask;

	public static DownloadManager getImageDownloader(Context context) {
		return (DownloadManager) GetSystemService.get(context, IMAGE_DOWNLOADER);
	}

	public void download(String url, ImageView imageView, BaseAdapter adapter) {
		if (url == null) {
			throw new IllegalArgumentException("url can not be null");
		}
		
		CacheManager.resetPurgeTimer();
        Bitmap bitmap = CacheManager.getBitmapFromCache(url);
        
        if (bitmap == null) {
        	imageView.setImageResource(R.drawable.stub);
            forceDownload(url, imageView, adapter);
        } else {
            imageView.setImageBitmap(bitmap);
        }
	}

	private void forceDownload(String url, ImageView imageView, BaseAdapter adapter) {
		if (asyncTask != null) {
			asyncTask.cancel(true);
		}
		asyncTask = new AsyncTaskManager(adapter);
		asyncTask.execute(url);
	}
}